﻿using MESMian.Common;
using MESMian.Context;
using System.Data;
using System.Drawing;

namespace MESMian.Forms
{
    public partial class TeamsList : Form
    {
        //搜索
        private TextBox txtSearch = new TextBox() { Enabled = false, Visible = false };
        private RectangleF searchTextRect;
        public TeamsList()
        {
            InitializeComponent();
            ucPager1.PagerEvent += UcPager1_PagerEvent;
            dataGridView1.CellPainting += DataGridView1_CellPainting;
            dataGridView1.CellMouseClick += DataGridView1_CellMouseClick;
            dataGridView1.ScrollBars = ScrollBars.Both;
            Load += TeamsList_Load;

            btnLook.Click += BtnLook_Click;

            txtTeamInfo.Visible = false;
            panel1.Paint += Panel1_Paint;
            panel1.MouseClick += Panel1_MouseClick;

            dateCreateStart.ValueChanged += DateCreateStart_ValueChanged;
            dateCreateEnd.ValueChanged += DateCreateEnd_ValueChanged;
            dateAlterStart.ValueChanged += DateAlterStart_ValueChanged;
            dateAlterEnd.ValueChanged += DateAlterEnd_ValueChanged;
            btnClearCreateStart.Click += BtnClearCreateStart_Click;
            btnClearCreateEnd.Click += BtnClearCreateEnd_Click;
            btnClearAlterStart.Click += BtnClearAlterStart_Click;
            btnClearAlterEnd.Click += BtnClearAlterEnd_Click;

        }



        /*  private void TeamsList_MouseClick(object? sender, MouseEventArgs e)
          {
              // 计算 txtSearch 在 TeamsList 中的实际显示位置
              Point txtSearchLocationInTeamsList = panel1.PointToClient(txtSearch.Parent.PointToScreen(txtSearch.Location));
              Rectangle txtSearchRectangle = new Rectangle(txtSearchLocationInTeamsList, txtSearch.Size);
              // 如果点击的范围不在 "搜索" 文本框内
              if (!txtSearch.Bounds.Contains(e.Location))
              {
                  if (txtSearch.Visible)
                  {
                      if (!string.IsNullOrWhiteSpace(txtSearch.Text))
                      {
                          // 如果 TextBox 有内容，执行查询
                          btnLook.PerformClick();
                      }
                      else
                      {
                          // 如果没有内容，隐藏 TextBox
                          txtSearch.Visible = false;
                      }
                  }
              }
          }*/

        private void BtnLook_Click(object? sender, EventArgs e)
        {
            ucPager1.CurrentPage = 1;
            ucPager1.GetPagerData();
        }

        #region 时间格式化
        private void BtnClearAlterEnd_Click(object? sender, EventArgs e)
        {
            dateAlterEnd.Format = DateTimePickerFormat.Custom;
            dateAlterEnd.CustomFormat = " ";
        }

        private void BtnClearAlterStart_Click(object? sender, EventArgs e)
        {
            dateAlterStart.Format = DateTimePickerFormat.Custom;
            dateAlterStart.CustomFormat = " ";

        }

        private void BtnClearCreateEnd_Click(object? sender, EventArgs e)
        {
            dateCreateEnd.Format = DateTimePickerFormat.Custom;
            dateCreateEnd.CustomFormat = " ";

        }

        private void BtnClearCreateStart_Click(object? sender, EventArgs e)
        {
            dateCreateStart.Format = DateTimePickerFormat.Custom;
            dateCreateStart.CustomFormat = " ";

        }

        private void DateAlterEnd_ValueChanged(object? sender, EventArgs e)
        {
            dateAlterEnd.Format = DateTimePickerFormat.Custom;
            dateAlterEnd.CustomFormat = "yyyy-MM-dd HH:mm:ss";
        }

        private void DateAlterStart_ValueChanged(object? sender, EventArgs e)
        {
            dateAlterStart.Format = DateTimePickerFormat.Custom;
            dateAlterStart.CustomFormat = "yyyy-MM-dd HH:mm:ss";
        }

        private void DateCreateEnd_ValueChanged(object? sender, EventArgs e)
        {
            dateCreateEnd.Format = DateTimePickerFormat.Custom;
            dateCreateEnd.CustomFormat = "yyyy-MM-dd HH:mm:ss";
        }

        private void DateCreateStart_ValueChanged(object? sender, EventArgs e)
        {
            dateCreateStart.Format = DateTimePickerFormat.Custom;
            dateCreateStart.CustomFormat = "yyyy-MM-dd HH:mm:ss";
        }
        #endregion

        #region 要求实现搜索
        private void Panel1_MouseClick(object? sender, MouseEventArgs e)
        {
            // 判断点击的位置是否在 "搜索" 文字的范围内
            if (searchTextRect.Contains(e.Location))
            {
                // 设置 TextBox 大小和位置与 "搜索" 文字一致
                txtSearch.Location = new Point((int)searchTextRect.X, (int)searchTextRect.Y);
                txtSearch.Size = new Size((int)searchTextRect.Width + 40, (int)searchTextRect.Height + 30);
                txtSearch.Visible = true;
                txtSearch.Enabled = true;
                // 将 TextBox 添加到 Panel 中
                panel1.Controls.Add(txtSearch);
                txtSearch.BringToFront();
                txtSearch.Focus();

                // 绑定按键事件，按下回车键后执行查询
                txtSearch.KeyDown += TxtSearch_KeyDown;
            }
            else
            {
                if (txtSearch.Visible)
                {
                    if (!string.IsNullOrWhiteSpace(txtSearch.Text))
                    {
                        btnLook.PerformClick();
                    }
                    else
                    {
                        txtSearch.Visible = false;
                    }

                }
            }
        }

        private void TxtSearch_KeyDown(object? sender, KeyEventArgs e)
        {
            btnLook.PerformClick();
        }
        private void Panel1_Paint(object? sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            System.Drawing.Font font = new System.Drawing.Font("微软雅黑", 28.8f, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF sizeSearch = e.Graphics.MeasureString("搜索", font);
            Point point = new Point(btnAdd.Location.X + +btnAdd.Width + 80, btnAdd.Location.Y);
            searchTextRect = new RectangleF(point, sizeSearch);
            g.DrawString("搜索", font, Brushes.Orange, searchTextRect);

        }
        #endregion


        private void TeamsList_Load(object? sender, EventArgs e)
        {   //绑定状态
            BindStatus();
            //将dataViewGrid中的状态颜色更改
            dataGridView1.CellFormatting += DataGridView1_CellFormatting;

            //时间的格式化
            dateCreateStart.Format = DateTimePickerFormat.Custom;
            dateCreateStart.CustomFormat = " ";
            dateCreateEnd.Format = DateTimePickerFormat.Custom;
            dateCreateEnd.CustomFormat = " ";
            dateAlterStart.Format = DateTimePickerFormat.Custom;
            dateAlterStart.CustomFormat = " ";
            dateAlterEnd.Format = DateTimePickerFormat.Custom;
            dateAlterEnd.CustomFormat = " ";

            ucPager1.GetPagerData();
        }

        private void DataGridView1_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "状态")
            {
                if (e.Value != null && e.Value.ToString() == "禁用")
                {
                    e.CellStyle.ForeColor = Color.Red;
                }
                else
                {
                    e.CellStyle.ForeColor = Color.Black;
                }
            }
        }

        private void BindStatus()
        {
            cbbStatus.Items.Clear();
            List<Status> list = new List<Status>()
            {
                new Status(){Code=-1,Text ="全部"},
                new Status(){Code=0,Text="正常"},
                new Status(){Code=1,Text="禁用"}
            };

            cbbStatus.DataSource = list;
            cbbStatus.DisplayMember = "Text";
            cbbStatus.ValueMember = "Code";
        }

        private void DataGridView1_CellMouseClick(object? sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Operate")
                {
                    Graphics g = dataGridView1.CreateGraphics();
                    System.Drawing.Font myFont = new System.Drawing.Font("宋体", 9F, FontStyle.Underline, GraphicsUnit.Point, 134);
                    SizeF sizeDel = g.MeasureString("禁用", myFont);
                    SizeF sizeMod = g.MeasureString("编辑", myFont);
                    SizeF sizeDet = g.MeasureString("详情", myFont);
                    SizeF sizeLog = g.MeasureString("启用", myFont);

                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fDet = sizeDet.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fLog = sizeLog.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);

                    Rectangle rectTotal = new Rectangle(0, 0, dataGridView1.Columns[e.ColumnIndex].Width, dataGridView1.Rows[e.RowIndex].Height);

                    RectangleF rectDel = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                    RectangleF rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);
                    RectangleF rectDet = new RectangleF(rectMod.Right, rectTotal.Top, rectTotal.Width * fDet, rectTotal.Height);
                    RectangleF rectLog = new RectangleF(rectDet.Right, rectTotal.Top, rectTotal.Width * fLog,
                       rectTotal.Height);

                    int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["班组ID"].Value);

                    #region 禁用
                    if (rectDel.Contains(curPosition))
                    {
                        using (var mtx = new MyContext())
                        {
                            var model = mtx.Teams.Find(id);
                            if (model!.Status == 0)
                            {
                                model!.Status = 1;
                                var query = mtx.Teams.Update(model);
                                mtx.SaveChangesAsync();
                                ucPager1.GetPagerData();
                            }
                            else
                            {
                                MessageBox.Show("该数据已经禁用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    #endregion

                    #region 启用
                    if (rectLog.Contains(curPosition))
                    {
                        using (var mtx = new MyContext())
                        {
                            var model = mtx.Teams.Find(id);
                            if (model!.Status == 1)
                            {
                                model!.Status = 0;
                                var query = mtx.Teams.Update(model);
                                mtx.SaveChangesAsync();
                                ucPager1.GetPagerData();
                            }
                            else
                            {
                                MessageBox.Show("该数据已经启用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    #endregion

                    #region 编辑 (待定)
                    if (rectMod.Contains(curPosition))
                    {
                        TeamsAdd teamsAdd = new TeamsAdd(id);

                    }

                    #endregion

                    #region 详情(待定)

                    #endregion

                }
            }
        }

        private void DataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Operate")
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    //取消背景色和dataview的颜色一致
                    e.PaintBackground(e.CellBounds, false);

                    System.Drawing.Font font = new System.Drawing.Font("微软雅黑", 9f, FontStyle.Regular, GraphicsUnit.Pixel);
                    SizeF sizeDel = e.Graphics.MeasureString("禁用", font);
                    SizeF sizeMod = e.Graphics.MeasureString("编辑", font);
                    SizeF sizeDet = e.Graphics.MeasureString("详情", font);
                    SizeF sizeLog = e.Graphics.MeasureString("启用", font);

                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fDet = sizeDet.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);
                    float fLog = sizeLog.Width / (sizeDel.Width + sizeMod.Width + sizeDet.Width + sizeLog.Width);

                    RectangleF rectDel = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);

                    RectangleF rectMod = new RectangleF(rectDel.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);

                    RectangleF rectDet = new RectangleF(rectMod.Right, e.CellBounds.Top, e.CellBounds.Width * fDet, e.CellBounds.Height);

                    RectangleF rectLog = new RectangleF(rectDet.Right, e.CellBounds.Top, e.CellBounds.Width * fLog,
                        e.CellBounds.Height);

                    e.Graphics.DrawString("禁用", font, Brushes.Red, rectDel, sf);
                    e.Graphics.DrawString("编辑", font, Brushes.Orange, rectMod, sf);
                    e.Graphics.DrawString("详情", font, Brushes.Blue, rectDet, sf);
                    e.Graphics.DrawString("启用", font, Brushes.Pink, rectLog, sf);

                    e.Handled = true;

                }
            }
        }

        private void UcPager1_PagerEvent(int currentPage, int pageSize, out int totalCount)
        {
            using (var mtx = new MyContext())
            {       //1.
                    //2. query1   query2    query3.
                    //3.DTO  1.
                    //4.DTO  2.
                var query = from tm in mtx.TeamMembers
                            join t in mtx.Teams on tm.TeamId equals t.TeamId
                            join u1 in mtx.Users on t.TeamContact equals u1.UserId
                            join u in mtx.Users on tm.MemberId equals u.UserId
                            //------------------------------------------------
                            join u2 in mtx.Users on tm.CreateUserId equals u2.UserId
                            join u3 in mtx.Users on tm.LastUpdateUserId equals u3.UserId
                            orderby tm.Status ascending
                            group new { t, u1, u, tm, u2, u3 } by new
                            {
                                t.TeamId,
                                t.TeamName,
                                t.TeamContact,
                                u1.UserName,
                                u1.Phone,
                                tm.Status,
                                创建人 = u2.UserName,
                                tm.CreateTime,
                                修改人 = u3 != null ? u3.UserName : null,
                                tm.LastUpdateTime
                            } into g
                            select new
                            {
                                班组ID = g.Key.TeamId,
                                班组名称 = g.Key.TeamName,
                                班组主要负责人ID = g.Key.TeamContact,
                                班组主要负责人 = g.Key.UserName,
                                班组负责人联系号码 = g.Key.Phone,
                                状态 = g.Key.Status == 0 ? "正常" : "禁用",
                                创建人 = g.Key.UserName,
                                创建时间 = g.Key.CreateTime,
                                修改人 = g.Key.UserName,
                                修改时间 = g.Key.LastUpdateTime,
                                班组成员 = string.Join(", ", g.Select(x => x.u.UserName))
                            };

                #region 查询
                if (!string.IsNullOrWhiteSpace(txtSearch.Text))
                {
                    query = query.Where(item =>
                    item.班组名称.Contains(txtSearch.Text) |
                    item.班组主要负责人.Contains(txtSearch.Text));
                }

                if (!string.IsNullOrWhiteSpace(dateCreateStart.Text))
                {
                    DateTime date = Convert.ToDateTime(dateCreateStart.Value.ToString("yyyy-MM-dd") + "00:00:00");
                    query = query.Where(item => item.创建时间 >= date);
                }
                if (!string.IsNullOrWhiteSpace(dateCreateEnd.Text))
                {
                    DateTime date = Convert.ToDateTime(dateCreateEnd.Value.ToString("yyyy-MM-dd") + "00:00:00");
                    query = query.Where(item => item.创建时间 <= date);
                }
                if (!string.IsNullOrWhiteSpace(dateAlterStart.Text))
                {
                    DateTime date = Convert.ToDateTime(dateAlterStart.Value.ToString("yyyy-MM-dd") + "00:00:00");
                    query = query.Where(item => item.修改时间 >= date);
                }
                if (!string.IsNullOrWhiteSpace(dateAlterEnd.Text))
                {
                    DateTime date = Convert.ToDateTime(dateAlterEnd.Value.ToString("yyyy-MM-dd") + "00:00:00");
                    query = query.Where(item => item.修改时间 <= date);
                }

                if (cbbStatus.SelectedItem != null)
                {
                    Status status = cbbStatus.SelectedItem as Status;
                    if (status!.Text != "全部")
                    {
                        query = query.Where(item => item.状态 == status.Text);
                    }
                }

                #endregion




                totalCount = query.Count();

                int skipNum = (currentPage - 1) * pageSize;
                //查询数据
                var data = query.Skip(skipNum).Take(pageSize).ToList();
                dataGridView1.DataSource = data;

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                #region 显示
                dataGridView1.Columns["班组主要负责人ID"].Visible = false;
                dataGridView1.Columns["班组ID"].Visible = false;

                dataGridView1.Columns["创建人"].DefaultCellStyle.Format = "yyyy-MM-dd Hh:mm";
                dataGridView1.Columns["修改人"].DefaultCellStyle.Format = "yyyy-MM-dd Hh:mm";


                if (!dataGridView1.Columns.Contains("Operate"))
                {
                    dataGridView1.Columns.Add("Operate", "操作");
                    dataGridView1.Columns["Operate"].Width = 200;
                }

                #endregion

            }
        }

    }
}
